package com.os.opencv.java.chapter13;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.video.BackgroundSubtractor;
import org.opencv.video.Video;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;

public class Mog2 {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        //打开时视屏文件
        VideoCapture vc = new VideoCapture("pics/2023-11-29_19-50-14.mp4");
        Mat frame = new Mat();  //保存读取的第一帧图像
        Mat fgMask = new Mat();  //保存提取的前景图像

        //创建mog2背景分割器
        BackgroundSubtractor subtractor;
        subtractor = Video.createBackgroundSubtractorMOG2();

        while(true){
            //读取视屏的第一帧
            vc.read(frame);

            //如果文件读取完，则退出循环
            if(frame.empty()){
                break;
            }

            //提取帧号
            double n = vc.get(Videoio.CAP_PROP_POS_FRAMES);

            //用mog2提取前景并在屏幕上显示
            subtractor.apply(frame, fgMask);
            Imgproc.putText(fgMask, String.valueOf(n), new Point(10, 30), 0, 1.0, new Scalar(255,255,255), 3);
            HighGui.imshow("fgMask", fgMask);
            int keyboard = HighGui.waitKey(30);

            //按esc键，则退出
            if(keyboard == 27) break;
        }
        HighGui.waitKey();
    }
}
